package com.orange.adminapi.controller.system;

import com.orange.adminapi.service.permission.RoleService;
import com.orange.core.pojo.BR;
import com.orange.core.pojo.R;
import com.orange.core.pojo.entity.permission.Permission;
import com.orange.core.pojo.entity.permission.Role;
import com.orange.core.pojo.enums.EStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/role")
public class RoleController {

    private final RoleService roleService;

    /**
     * 列表
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).ROLE_LIST.permission.identifier)")
    @PostMapping("/list")
    public R<List<Role>> list() {
        return R.ok(roleService.list());
    }

    /**
     * 获取有效角色
     */
    @PostMapping("/validList")
    public R<List<Role>> validList() {
        return R.ok(roleService.validList(null));
    }

    /**
     * 详情
     */
    @GetMapping("/{id}")
    public R<Role> detail(@PathVariable(value = "id", required = false) Role role) {
        return R.ok(roleService.detail(role));
    }

    /**
     * 保存
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).ROLE_ADD.permission.identifier)")
    @PostMapping
    public R<Boolean> save(@RequestBody Role role) {
        return BR.result(roleService.save(role));
    }

    /**
     * 编辑
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).ROLE_EDIT.permission.identifier)")
    @PutMapping
    public R<Boolean> update(@RequestBody Role role) {
        return BR.result(roleService.update(role));
    }

    /**
     * 启用/禁用
     *
     * @param status 状态：0禁用，1启用
     */
    @PreAuthorize("hasAuthority(T(com.orange.core.pojo.enums.EPermission).ROLE_STATUS.permission.identifier)")
    @PostMapping("/{id}/status/{status}")
    public R<Boolean> setStatus(@PathVariable int id, @PathVariable(value = "status", required = false) EStatus status) {
        return BR.result(roleService.setStatus(id, status));
    }

    /**
     * 权限列表
     */
    @GetMapping("/permissions")
    public R<List<Permission>> permissions() {
        return R.ok(roleService.permissionTree());
    }
}
